package com.sinopec.handdevice.view

import android.Manifest
import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter.LengthFilter
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import com.alibaba.android.arouter.facade.annotation.Route
import com.gyf.immersionbar.ImmersionBar
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.widget.textChanges
import com.sinopec.basemodule.AppConstants
import com.sinopec.basemodule.BaseApplication
import com.sinopec.basemodule.base.BaseActivity
import com.sinopec.basemodule.base.CustomToolbar
import com.sinopec.basemodule.common.CommonVebViewActivity
import com.sinopec.basemodule.common.Logger
import com.sinopec.basemodule.dialog.CommonTipsPopupWindow
import com.sinopec.basemodule.model.UserInfo
import com.sinopec.basemodule.router.ReflectUtils
import com.sinopec.basemodule.utils.ARouterManagerUtils
import com.sinopec.basemodule.utils.PhoneUtils
import com.sinopec.basemodule.utils.StringUtils
import com.sinopec.basemodule.utils.ToastUtils
import com.sinopec.handdevice.BuildConfig
import com.sinopec.handdevice.MyApp
import com.sinopec.handdevice.R
import com.sinopec.handdevice.contract.LoginContract
import com.sinopec.handdevice.inputFilter.ChineseInputFilter
import com.sinopec.handdevice.presenter.LoginPresenter
import com.tbruyelle.rxpermissions2.RxPermissions
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.BiFunction
import kotlinx.android.synthetic.main.activity_login.*
import java.util.concurrent.TimeUnit

/**
 * @author lwj
 * @ClassName: LoginActivity
 * @Description: 登录页面
 * @date 2019/6/25 14:12
 */
@Route(path = ARouterManagerUtils.GOTO_MAIN_LOGIN_ACTIVITY)
open class LoginActivity : BaseActivity<LoginPresenter?>(), LoginContract.View {

    private val TAG = "LoginActivity"
    override fun getContentView(): Int {
        return R.layout.activity_login
    }

    override fun configToolbar(rToolbar: CustomToolbar) {
        rToolbar.setToolbarVisible(false)
    }

    override fun setStatusBar() {
        super.setStatusBar()
        ImmersionBar.with(this).statusBarDarkFont(true).init()
    }

    override fun initView(savedInstanceState: Bundle?) {
        //BaseApplication.getInstance().appUpdateEvent(false)

        //账号编辑
        et_username.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                Logger.i(TAG, "s=$s start=$start count=$count after=$after")
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                Logger.i(TAG, "s=$s start=$start before=$before count=$count")
                if (s.isNotEmpty()) {
                    iv_clear.visibility = View.VISIBLE
                } else {
                    iv_clear.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable) {
                Logger.i(TAG, "s=$s")
            }
        })
        //密码清除按钮
        et_pwd.filters = arrayOf(
            LengthFilter(16), ChineseInputFilter()
        )
        et_pwd.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
                Logger.i(TAG, "s=$s start=$start count=$count after=$after")
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                Logger.i(TAG, "s=$s start=$start before=$before count=$count")
                if (s.isNotEmpty()) {
                    iv_clear_password.visibility = View.VISIBLE
                } else {
                    iv_clear_password.visibility = View.GONE
                }
            }

            override fun afterTextChanged(s: Editable) {
                Logger.i(TAG, "s=$s")
            }
        })
        //密码显示
        cb_hide_password.setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener { buttonView, isChecked ->
            Logger.d(TAG, "onCheckedChanged: $isChecked")
            if (isChecked) {
                //选择状态 显示明文--设置为可见的密码
                et_pwd.inputType = InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
                et_pwd.setSelection(et_pwd.length())
            } else {
                //默认状态显示密码--设置文本 要一起写才能起作用 InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD
                et_pwd.inputType =
                    InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                et_pwd.setSelection(et_pwd.length())
            }
        })

        //测试时候的配置信息
        if (BuildConfig.DEBUG) {
            findViewById<View>(R.id.iv_logo).setOnLongClickListener { v: View? ->
                navigationTo(DebugActivity::class.java)
                true
            }
        }
        val userNameObservable = et_username.textChanges()
            .map { obj: CharSequence -> obj.toString() }
            .map { driverPhone: String? -> !driverPhone.isNullOrEmpty() }
        val pwdObservable = et_pwd.textChanges()
            .map { obj: CharSequence -> obj.toString() }
            .map { msgCode: String? -> StringUtils.checkPwd(msgCode) }
        addDisposable(Observable
            .combineLatest(userNameObservable,
                pwdObservable,
                BiFunction { nameIsAvailable: Boolean, pwdIsAvailable: Boolean -> nameIsAvailable && pwdIsAvailable })
            .subscribe { enable: Boolean? -> tv_login.isEnabled = enable!! })

        //有用户信息就进入主界面
        if (MyApp.getInstance().userManager.user != null
            && MyApp.getInstance().token != null
        ) {
            ReflectUtils.navigationToHome(mContext, 0)
            mContext.finish()
        }
        tv_version_name.text = BaseApplication.getInstance().versionName
        tv_icp.paintFlags = tv_icp.paintFlags or Paint.UNDERLINE_TEXT_FLAG
        //获取设备号
        refreshDeviceId()
    }

    override fun initData() {
        super.initData()
        mPresenter = LoginPresenter(this)
    }

    /**
     * 设置事件监听
     */
    @SuppressLint("ClickableViewAccessibility")
    override fun initEvent() {
        super.initEvent()

        /**
         * 检查更新
         */
        addDisposable(ll_version.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                //检查更新
                //BaseApplication.getInstance().appUpdateEvent(true)
            })

        /**
         * 跳转备案号界面
         */
        addDisposable(tv_icp.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .subscribe {
                CommonVebViewActivity.startActivity(
                    mContext,
                    AppConstants.ICP_URL,
                    "ICP/IP地址/域名信息备案管理系统"
                )
            })

        /**
         * 登录按钮
         */
        addDisposable(tv_login!!.clicks()
            .throttleFirst(1, TimeUnit.SECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { login() })
        /**
         * 清空账号
         */
        addDisposable(iv_clear!!.clicks()
            .subscribe { et_username!!.setText("") })
        /**
         * 清空密码
         */
        addDisposable(iv_clear_password!!.clicks()
            .subscribe { et_pwd!!.setText("") })
        /**
         * 忘记密码
         */
        addDisposable(tv_forget_password!!.clicks()
            .subscribe {
                //跳转找回密码
                //ForgetPasswordActivity.startActivity(this);
                //Beta.checkUpgrade(true, false)
            })
    }

    /**
     * 点击登录
     */
    private fun login() {
        //登录用户名（手机号码）密码、验证码
        var userPhone = et_username!!.text.toString()
        if (!TextUtils.isEmpty(userPhone) && userPhone.contains("-")) {
            userPhone = userPhone.replace("-", "")
        }
        val passwordOrCode = et_pwd!!.text.toString()
        val deviceId = tv_device_id!!.text.toString()
        if (!TextUtils.isEmpty(deviceId)) {
            //网络请求登录
            //mPresenter!!.login(userPhone, passwordOrCode, deviceId)
            //模拟登录成功流程
            val token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyblN0ciI6IlNGMHBFUWp6MWRYc0swNkY0dExsd3NRbFN5cXhkUUVDIn0.VEq1Y_ZPeBeTR412szW2zjwFmcmdu4t8BJMz1YAtNHE"
            BaseApplication.getInstance().updateToken(token)
            val userInfo = UserInfo()
            userInfo.userId = "123"
            userInfo.userName = userPhone
            userInfo.userAccount = userPhone
            BaseApplication.getInstance().userManager.user = userInfo
            ReflectUtils.navigationToHome(mContext, 0)
            mContext.showMessage("登录成功")
            mContext.finish()
        } else {
            refreshDeviceId()
        }
    }

    /**
     * 获取设备号
     */
    private fun refreshDeviceId() {
        addDisposable(RxPermissions(this@LoginActivity)
            .request(Manifest.permission.READ_PHONE_STATE)
            .subscribe { aBoolean ->
                if (aBoolean) {
                    @SuppressLint("MissingPermission") val deviceId = PhoneUtils.getDeviceId()
                    tv_device_id_label!!.text = "设备ID："
                    tv_device_id!!.text = deviceId
                    Log.i(TAG, "设备ID：" + deviceId)
                } else {
                    ToastUtils.showToast("请允许获取手机读取权限！")
                }
            })
    }

    /**
     * 登录失败
     */
    override fun loginError(msg: String?) {
        if (!TextUtils.isEmpty(msg)) {
            tv_error.text = msg
            ll_error.visibility = View.VISIBLE
        } else {
            ll_error.visibility = View.GONE
        }
    }
}